<template>
    <div>
        <el-row>
            <el-col :lg="12">
                <el-form ref="form" :rules="rules" :model="form" label-width="100px" v-loading="loading">
                    <el-form-item label="组名" prop="name" required>
                        <el-input v-model="form.name" placeholder="组名"></el-input>
                    </el-form-item>

                    <el-form-item label="权限" prop="access">

                        <el-card class="role-access-card" v-for="(pVal, pKey) in access" :key="pKey" v-loading="accessLoading">
                            <!-- 一级菜单(有子类) -->
                            <div slot="header" class="clearfix" v-if="pVal.child">
                                <el-checkbox
                                    v-model="selectedAll[pKey]"
                                    @change="handleCheckAllChange($event, pKey)"
                                    :indeterminate="isIndeterminate[pKey]">
                                    {{ pVal.name }}
                                </el-checkbox>
                            </div>
                            <template v-if="pVal.child">
                                <el-checkbox-group v-model="selected">
                                    <el-checkbox
                                        @change="handleCheckedChange($event, pKey)"
                                        v-for="cVal in pVal.child"
                                        :label="cVal.id"
                                        :key="cVal.id">
                                        {{ cVal.name }}
                                    </el-checkbox>
                                </el-checkbox-group>
                            </template>
                            <!-- 一级菜单(无子类) -->
                            <template v-else>
                                <el-checkbox
                                    v-model="selected"
                                    :label="pVal.id"
                                    :key="pVal.id">
                                    {{ pVal.name }}
                                </el-checkbox>
                            </template>
                        </el-card>

                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="submit" :loading="submitLoading">保存</el-button>
                        <el-button @click="$router.go(-1)">返回</el-button>
                    </el-form-item>
                </el-form>
            </el-col>
            <el-col :lg="11" :offset="1">
                <h3>关联渠道</h3>
                <checkbox-app-source v-model="form.sources"></checkbox-app-source>
            </el-col>
        </el-row>
    </div>
</template>

<script>
import CheckboxAppSource from '~/components/Checkbox/app-source';

export default {
    components: {
        CheckboxAppSource,
    },
    data() {
        return {
            loading: false,
            accessLoading: false,
            submitLoading: false,
            form: {
                id: 0,
                name: '',
                access: [],
                status: 1,
                sources: [],
            },
            isIndeterminate: {},
            access: [],
            selectedAll: {},
            selected: [],
            locked: false,
            rules: {
                name: [
                    { required: true, message: '请输入组名', trigger: 'blur' },
                ],
            },
        }
    },
    watch: {
        access() {
            if (!this.locked) this.autoSelected();
        },
        selected() {
            if (!this.locked) this.autoSelected();
        }
    },
    methods: {
        getFormAction() {
            return this.form.id ? 'role/Update' : 'role/Store';
        },
        // 获取数据
        getData() {
            this.loading = true;
            this.$store.dispatch('role/Show', this.form.id).then(res => {
                this.form = res.data;
                if (!this.form.sources) this.form.sources = [];
                this.selected = this.form.role_access.map(v => {
                    return v.id;
                }) || [];
            }).finally(() => {
                this.loading = false;
            });
        },
        // 提交
        submit() {
            this.$refs.form.validate(valid => {
                if (!valid) return false;
                this.submitLoading = true;
                this.$store.dispatch(this.getFormAction(), this.handleFormData()).then(res => {
                    this.$message.success(res.data.message);

                    // 更新角色缓存
                    this.$store.dispatch('role/All', 'role');

                    this.$router.go(-1);
                }).finally(() => {
                    this.submitLoading = false;
                });
            });
        },
        // 获取所有权限
        getAllAccess() {
            this.accessLoading = true;
            this.$store.dispatch('roleAccess/Format').then(res => {
                this.access = res.data.data;
                // 预定义
                //this.access.map((v, k) => {  this.isIndeterminate[k] = false; });
            }).finally(() => {
                this.accessLoading = false;
            });
        },
        // 处理form-data, 移除无用权限
        handleFormData() {
            let selected = this.selected.slice(); // 防止浅拷贝
            let form = Object.assign({}, this.form);

            // 如果选中了所有权限(权限*), 移除其它权限
            if (selected.indexOf(1) > -1 || selected.indexOf('1') > -1) {
                form.access = [1];
                return form;
            }
            // 排序
            form.access = selected.sort((a, b) => {
                return a > b ? 1 : -1;
            });
            return form;
        },
        // 顶级权限选中|取消, 自动选中|取消子级权限
        handleCheckAllChange(val, pKey) {
            //console.log('handleCheckAllChange', val, pKey);
            if (!this.access[pKey].child || !this.access[pKey].child.length) {
                return;
            }
            this.isIndeterminate[pKey] = false;
            if (val) {
                this.access[pKey].child.map(v => {
                    if (this.selected.indexOf(v.id) === -1) this.selected.push(v.id);
                });
            } else {
                this.access[pKey].child.map(v => {
                    if (this.selected.indexOf(v.id) > -1) this.selected.splice(this.selected.indexOf(v.id), 1);
                });
            }
        },
        // 子级选中|取消, 检查顶级权限是否需要选中|取消
        handleCheckedChange(val, pKey) {
            //console.log('handleCheckedChange', val, pKey);
            if (!this.access[pKey].child || !this.access[pKey].child.length) return;
            let childRouteArr = this.access[pKey].child.map(v => { return v.id; });
            let checkedLength = this.selected.filter(v => childRouteArr.includes(v)).length;
            this.isIndeterminate[pKey] = checkedLength > 0 && checkedLength < childRouteArr.length;
            this.selectedAll[pKey] = checkedLength === childRouteArr.length;
        },
        // 自动选择
        autoSelected() {
            if (!this.access.length || !this.selected.length) return;
            this.locked = true;

            // 遍历所有顶级, 确认选中状态
            for (let i in this.access) this.handleCheckedChange(true, i);
        }
    },
    created() {
        this.getAllAccess();
        if (this.$route.params.id) {
            this.form.id = this.$route.params.id;
            this.getData();
        } else {
            this.loading = false;
        }
    }
}
</script>

<style lang="scss" scoped>

    .role-access-card {
        margin: 0 0 10px 0;
        .el-card__header,.el-card__body {
            line-height: 19px;
        }
        .el-card__body:empty {
            padding: 0;
        }
    }
</style>

